package com.template.config.webmvc;

import com.template.common.JacksonObjectMapper;
import com.template.config.webmvc.interceptor.*;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {

    private final FileUploadInterceptor fileUploadInterceptor;

    private final UserPermissionInterceptor userPermissionInterceptor;

    private final IdentityInterceptor identityInterceptor;

    private final PermissionAliveInterceptor permissionAliveInterceptor;

    // 拦截路径白名单
    private static final String[] excludePathPatterns = {
            "/auth/captcha",
            "/auth/valid-captcha",
            "/auth/phone-code",
            "/auth/email-code",
            "/auth/login",
            "/auth/logout",
            "/test/**",
            "/ws/**"
    };

    /**
     * 拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CorsInterceptor())
                .addPathPatterns("/**")
                .order(0);
        registry.addInterceptor(fileUploadInterceptor)
                .addPathPatterns("/**")
                .order(1);
        // validToken 必须放置在 Authority拦截器 之前
        registry.addInterceptor(identityInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(excludePathPatterns)
                .order(2);
        registry.addInterceptor(userPermissionInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(excludePathPatterns)
                .order(3);
        registry.addInterceptor(permissionAliveInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(excludePathPatterns)
                .order(4);
    }

    /**
     * 扩展MVC消息转换器
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        // 设置对象转换器，底层使用Jackson将Java对象转换为json
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        // 将上面的消息转换器对象追加到MVC框架的转换器集合中
        converters.add(0, messageConverter);
    }
}
